package com.maxwell.googleplay.base;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseStream;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.maxwell.googleplay.bean.HomeBean;
import com.maxwell.googleplay.conf.Constants;
import com.maxwell.googleplay.conf.Constants.URL;
import com.maxwell.googleplay.utils.FileUtils;
import com.maxwell.googleplay.utils.IOUtils;

/**
 * @author yue
 * @创建时间 2016-4-1上午9:05:25
 * @描述 TODO
 * 
 */
/**
 * @author yue
 * @创建时间 2016-4-1上午9:45:15
 * @描述 TODO
 */
public abstract class BaseProtocol<T> {

	public T loadData(int index) throws Exception {

		/* ==========读取本地缓存============= */
		T localData = getDataFromLocal(index);
		if (localData != null) {

			return localData;
		}
		/* ==========发送网络请求，拿到json格式的数据============= */
		String jsonString = getDataFromNet(index);

		/* ==========解析数据============= */
		// Gson gson = new Gson();
		T homeBean = parseJson(jsonString);
		return homeBean;

	}

	/**
	 * @desc 读取本地数据
	 * @param index
	 * @return
	 */
	private T getDataFromLocal(int index) {
		File cacheFile = getCacheFile(index);
		if (cacheFile.exists()) {
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new FileReader(cacheFile));
				String timeTimeMillis = reader.readLine();
				if ((System.currentTimeMillis() - Long
						.parseLong(timeTimeMillis)) < Constants.PROTOCOLTIMEOUT) {
					// 读取缓存内容
					String jsonString = reader.readLine();
					return parseJson(jsonString);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				IOUtils.close(reader);
			}
		}

		return null;
	}

	public File getCacheFile(int index) {
		String dir = FileUtils.getDir("json");
		
		
		Map<String, String> extraParams = getExtraParams();
		String name = "";
		if(extraParams == null){
			name = getInterfaceKey() + "." + index;
		}else{//如果是详情页
			for (Map.Entry<String, String> info : extraParams.entrySet()) {
				String key = info.getKey();
				String value = info.getValue();
				name = getInterfaceKey() + "." + value;
			}
		}
		
		File cacheFile = new File(dir, name);
		return cacheFile;
	}

	/**
	 * @return 返回额外的参数
	 */
	public Map<String, String> getExtraParams(){
		return null;
	}
	
	
	public String getDataFromNet(int index) throws HttpException, IOException {
		HttpUtils httpUtils = new HttpUtils();
		String url = URL.BASEURL + getInterfaceKey();

		RequestParams params = new RequestParams();
		Map<String, String> extraParams = getExtraParams();
		if(extraParams == null){
			params.addQueryStringParameter("index", index + "");
		}else{
			//取出额外的参数
			for (Map.Entry<String, String> info : extraParams.entrySet()) {
				String name = info.getKey();
				String value = info.getValue();
				params.addQueryStringParameter(name, value);
			}
		}
		
		ResponseStream responseStream = httpUtils.sendSync(HttpMethod.GET, url,
				params);
		String jsonString = responseStream.readString();

		// 保存网络数据到本地
		File cacheFile = getCacheFile(index);
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(cacheFile));
			writer.write(System.currentTimeMillis() + "");// 第一行写入插入事件
			writer.write("\r\n");// 换行
			writer.write(jsonString);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			IOUtils.close(writer);
		}

		return jsonString;
	}

	public abstract String getInterfaceKey();

	public abstract T parseJson(String jsonString);

}
